import {read, utils} from 'xlsx';

const csvToJson = {
    load (file, callback) {
        let reader = new FileReader();
        reader.readAsText(file, 'gbk');
        reader.onload = evt => {
            let result = evt.target.result;
            callback(this.csvToJson(result));
        };
    },
    csvToJson (result) {
        result = result.split('\n');
        let head = result[0].split(',');
        let newArr = [];
        for (let i = 1; i < result.length - 1; i++) {
            newArr.push(result[i].split(','));
        }
        let jsonArray = [];
        let obj;
        for (let i = 0; i < newArr.length; i++) {
            let arr = {};
            arr['key'] = i + 1;
            for (let j = 0; j < head.length; j++) {
                arr[head[j]] = newArr[i][j];
            }
            jsonArray.push(arr);
        }
        obj = {
            head: head,
            data: jsonArray
        };
        return obj;
    },
    /**
     * 读取网络Excel文件
     * @param serviceUrl
     * @param callback
     */
    readExcel (serviceUrl, callback) {
        let xhr = new XMLHttpRequest();
        xhr.open('get', serviceUrl, true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function (e) {
            if (xhr.status === 200) {
                let data = new Uint8Array(xhr.response);
                let workbook = read(data, { type: 'array' });
                if (callback) callback(workbook);
            }
        };
        xhr.send();
    },
    /**
     * 获取Excel内容转为json
     * @param fileUrl
     * @param callback
     */
    getExcelToJson (fileUrl, callback) {
        this.readExcel(fileUrl, result => {
            let sheetNames = result.SheetNames;
            let data = {};
            for (const sheetNamesKey in sheetNames) {
                if (sheetNames.hasOwnProperty(sheetNamesKey)){
                    let worksheet = result.Sheets[sheetNames[sheetNamesKey]];
                    data[sheetNames[sheetNamesKey]] = utils.sheet_to_json(worksheet);
                }
            }
            callback(data);
        });
    },
};

export default csvToJson;